package handler

import (
	"context"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/garyburd/redigo/redis"
	"github.com/micro/go-micro/util/log"
	"ihome/models"
	"ihome/utils"

	userAuth "ihome/proto/userAuth"
)

type UserAuth struct{}

// Call is a single request handler called via client.Call or the generated client code
func (e *UserAuth) SrvUserAuth(ctx context.Context, req *userAuth.Request, rsp *userAuth.Response) error {
	logs.Info("实名认证 UserAuth /api/v1.0/user/auth")

	rsp.Code = utils.RecodeOk
	rsp.Msg = utils.RecodeText(rsp.Code)

	bm, err := utils.NewCache()
	if err != nil {
		logs.Info("redis连接失败", err)
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}
	sessionId := req.SessionId
	userIdObj := bm.Get(sessionId + "user_id")
	userId, _ := redis.Int(userIdObj, nil)

	user := models.User{
		Id: userId,
		Real_name: req.RealName,
		Id_card: req.IdCard,
	}
	o := orm.NewOrm()
	_, err = o.Update(&user, "real_name", "id_card")

	if err != nil {
		logs.Info("身份信息更新失败")
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	//bm.Put(sessionId+"name", user.Mobile, time.Second*3600)
	//bm.Put(sessionId+"user_id", user.Id, time.Second*3600)
	//bm.Put(sessionId+"mobile", user.Mobile, time.Second*3600)

	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *UserAuth) Stream(ctx context.Context, req *userAuth.StreamingRequest, stream userAuth.UserAuth_StreamStream) error {
	log.Logf("Received UserAuth.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Logf("Responding: %d", i)
		if err := stream.Send(&userAuth.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *UserAuth) PingPong(ctx context.Context, stream userAuth.UserAuth_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Logf("Got ping %v", req.Stroke)
		if err := stream.Send(&userAuth.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
